<template>
  <div class="create-page">
    <div class="left-slide">
      <List @nodeClick="handleNodeClick" ref="structureListRef"/>
    </div>
    <div class="right-form-container">
      <div class="header-box">
        <div>
          <el-button   type="info" @click="addOrg">新增部门</el-button>
        </div>
        <div>
        </div>
      </div>
      <div class="table-container">
        <div class="table-box">
          <el-table
              :data="tableData"
              :height="'100%'"
              border
              :header-cell-style="{textAlign:'center'}"
              :cell-style="{textAlign:'center'}"
          >
            <!--            <el-table-column type="selection" />-->
            <el-table-column prop="name" label="部门名称" width="200px">
              <template slot-scope="scope">
                <el-tag>{{scope.row.name}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="id" label="唯一编码" />
            <el-table-column prop="level" label="部门等级">
              <template slot-scope="scope">
                {{convertToChineseNumeral(scope.row.level)+'级单元'}}
              </template>
            </el-table-column>
            <el-table-column prop="parent_name" label="父级名称" />
            <el-table-column prop="level" label="父级等级">
              <template slot-scope="scope">
                {{convertToChineseNumeral(scope.row.parent_level)+'级单元'}}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <span :style="scope.row.status === true ? 'color:green':'color:red'">{{scope.row.status === true ? '有效':'无效'}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="240">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="check(scope.row)">编辑</el-button>
                <el-button type="warning" :style="scope.row.status === true ? 'background-color:red':'background-color:green'" size="mini" @click="changeStatus(scope.row.id)">
                  <span style="color: white">{{scope.row.status === true?'禁用':'启用'}}</span>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="table-pagination">
          <!-- 分页 -->
          <el-pagination
              :current-page.sync="paginations.page_index"
              :page-sizes="paginations.page_sizes"
              :page-size="paginations.page_size"
              :layout="paginations.layout"
              background
              :total="paginations.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <EditDepartment ref="editDepartmentRef" :form-data="currentRow" @callback="handleEditorCallBack"/>
  </div>
</template>
<script>
import List from '@/components/List.vue';
import EditDepartment from '@/components/editDepartment.vue';
import {deptInfo, deptSelectByParent, deptStatusChange} from "@/utils/dept";
export default {
  name: 'depManage',
  components: {
    List,
    EditDepartment
  },
  props: {},
  data() {
    return {
      paginations: {
        page_index: 1, //当前位于哪页
        total: 0, //数据总数
        page_size: 10, //一页显示多少条
        page_sizes: [5, 10, 15, 20,50,100], //每页显示多少条
        layout: "total, sizes, prev, pager, next, jumper", //翻页属性
      },
      allTableData:[],
      tableData: [],
      currentRow: null,
      parent_id: '1'
    }
  },
  created() {},
  mounted() {
    this.getTableData();
  },
  methods: {
    convertToChineseNumeral(num) {
      if (num === 10) {
        return '十'
      } else if (num === 1) {
        return '一'
      }
      const digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
      const units = ['', '十', '百', '千', '万'];
      let result = '';
      let numStr = num.toString();
      for (let i = 0; i < numStr.length; i++) {
        let digit = parseInt(numStr.charAt(i));
        let unit = units[numStr.length - i - 1];
        if (digit === 0) {
          // 当前数字为0时不需要输出汉字，但需要考虑上一个数字是否为0，避免出现连续的零
          if (result.charAt(result.length - 1) !== '零') {
            result += '零';
          }
        } else {
          result += digits[digit] + unit;
        }
      }
      // 对于一些特殊的数字，如10、100等，需要在最前面加上“一”
      if (result.charAt(0) === '一') {
        result = result.substr(1, result.length);
      } else if (result.charAt(0) === '百') {
        result = '一' + result;
      } else if (result.charAt(0) === '千') {
        result = '一' + result;
      }
      return result;
    },
    //设置分页属性
    setPaginations() {
      //初始化
      this.paginations.total = this.allTableData.length;
      this.paginations.page_index = 1;
      this.paginations.page_size = 10;
      //设置默认的分页数据
      this.tableData = this.allTableData.filter((item, index) => {
        return index < this.paginations.page_size;
      });
    },
    //分页方法
    handleCurrentChange(page) {
      //获取当前页
      let index = this.paginations.page_size * (page - 1);
      //获取数据总数
      let nums = this.paginations.page_size * page;
      //容器
      let tables = [];
      for (let i = index; i < nums; i++) {
        if (this.allTableData[i]) {
          tables.push(this.allTableData[i]);
        }
        this.tableData = tables;
      }
    },
    handleSizeChange(page_size) {
      this.paginations.page_index = 1;
      this.paginations.page_size = page_size;
      this.tableData = this.allTableData.filter((item, index) => {
        return index < page_size;
      });
    },
    handleEditorCallBack() {
      this.currentRow = null;
      this.getTableData();
      this.$refs['structureListRef'].getTreeData();
    },
    addOrg() {
      this.currentRow = null;
      this.$refs['editDepartmentRef'].showDialog();
    },
    handleNodeClick(val) {
      this.parent_id = val.id;
      this.getTableData();
    },
    check(row) {
      this.currentRow ={}
      let params = {
        dept_id:row.id
      }
      deptInfo(params).then(res =>{
        if(res.code === 1){
          let temp = JSON.stringify(res.data[0]);
          temp = temp.replace('id','dept_id')
          temp = temp.replace('name','dept_name')
          temp = temp.replace('assistant','assistant_id')
          temp = temp.replace('attendance','attendance_id')
          temp = temp.replace('leader','leader_id')
          temp = temp.replace('parent','parent_id')
          this.currentRow = JSON.parse(temp)
        }
      })
      this.$refs['editDepartmentRef'].showDialog();
    },
    changeStatus(id) {
      this.$confirm('确定更改部门状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deptStatusChange({ dept_id:id }).then(res => {
          if (res.code === "1") {
            this.$message({
              type: 'success',
              message: '更改部门状态成功!'
            });
            this.handleEditorCallBack();
          }
        })
        // eslint-disable-next-line no-unused-vars
      }).catch(_ => {})
    },
    getTableData() {
      const requestBody = {}
      if (this.parent_id && this.parent_id !== '') {
        requestBody.parent_id = this.parent_id;
      }
      deptSelectByParent(requestBody).then(res => {
        if (res.code === 1) {
          this.allTableData = res.data;
          this.setPaginations();
        }
      });
    }
  }
}
</script>
<style lang="scss" scoped>
.create-page {
  width: 100%;
  height: 88vh;
  //max-height: 690px;
  background-color: #fff;
  display: flex;
  .left-slide {
    width: 45%;
    height: 100%;
    border: 10px #f0f0f0 solid;
    text-align: center;
    padding-top: 20px;
    box-sizing: border-box;
    overflow: hidden;
  }
  .left-slide:hover{
    overflow: auto;
  }
  .right-form-container {
    //border: 10px #f0f0f0 solid;
    width: 80%;
    height: 100%;
    border-top: 10px #f0f0f0 solid;
    border-right: 10px #f0f0f0 solid;
    border-bottom: 10px #f0f0f0 solid;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    .header-box{
      width: 100%;
      background-color: #fff;
      padding: 10px 15px;
      display:flex;
      justify-content:space-between;
      align-items:center;
      //::v-deep .el-form-item{
      //  margin-right: 30px;
      //  .el-form-item__label{
      //    font-family: "Microsoft YaHei";
      //    color: #333
      //  }
      //}
    }
    .table-container{
      width: 100%;
      border-top: 10px #f0f0f0 solid;
      flex: 1;
      margin-top: 10px;
      display: flex;
      flex-direction: column;
      .table-box {
        width: 100%;
        flex-grow: 1;
        overflow: hidden;
        overflow-y: auto;
        a{
          color: #409EFF;
        }
      }
      .table-pagination{
        //height: 60px;
        width: 100%;
        text-align: right;
        background-color: #fff;
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        ::v-deep .el-pagination{
          margin-bottom: 10px;
          span, button, ul>li{
            //height: 50px;
            //line-height: 50px;
            //font-size: 16px;
          }
        }
      }
    }
  }
}
</style>
